import { JSDOM } from 'jsdom'
namespace webapizonghe {
    const dom: JSDOM = new JSDOM(`
        <!DOCTYPE html>
        <html>
          <body>
             <h2>Student List Management</h2>
  <div class="tools-header">
    <button class="openModalBtn">Add New Student</button>

    <div>
      <input type="text" name="keyword" class="keyword">
      <button type="button" class="searchBtn">检索</button>
    </div>
  </div>


  <table class="studentTable">
    <thead>
      <tr>
        <th><input type="checkbox" class="selectAll"></th>
        <th>ID</th>
        <th>Name</th>
        <th>Gender</th>
        <th>Hobbies</th>
        <th>邮箱</th>
        <th>手机号</th>
        <th>Age</th>
        <th>添加时间</th>
        <th>修改时间</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      <!-- Student rows will be added dynamically here -->
    </tbody>
  </table>

  <!-- 添加/修改学生信息的弹框 -->
  <div class="studentModal modal">
    <div class="modal-content">
      <h3 class="modalTitle">Add New Student</h3>
      <form class="studentForm">
        <input type="hidden" class="studentIdToEdit"> <!-- Hidden input to hold ID for editing -->

        <label for="studentName">Name</label>
        <input type="text" name="name" class="studentName" required>

        <label for="studentGender">Gender</label>
        <select name="gender" class="studentGender" required>
          <option value="Male">Male</option>
          <option value="Female">Female</option>
        </select>

        <label for="studentHobbies">Hobbies</label>
        <input type="text" name="hobbies" class="studentHobbies" required>

        <label for="studentIphone">手机号</label>
        <input type="text" name="iphone" class="studentIphone" required>

        <label for="studentEmail">邮箱</label>
        <input type="text" name="email" class="studentEmail" required>

        <label for="studentAge">Age</label>
        <input type="number" name="age" class="studentAge" required>

        <button type="submit" class="saveStudentBtn">Save Student</button>
      </form>
    </div>
  </div>
          </body>
        </html>
        `);
    const document: Document = dom.window.document;

    interface Student {
        id: number;
        name: string;
        gender: string;
        hobbies: string;
        email?: string;
        iphone?: string;
        age: number;
        create_at?: string;
        update_at?: string;
    }

    let students: Student[] = [
        { id: 1, name: 'Alice', gender: 'Female', hobbies: 'Reading', age: 20 },
        { id: 2, name: 'Bob', gender: 'Male', hobbies: 'Sports', age: 22 },
        { id: 3, name: 'Charlie', gender: 'Male', hobbies: 'Gaming', age: 21 }
    ];

    let keyword: string = '';
    let searchStudents: Student[] = [];

    const searchBtnEl = document.querySelector('.searchBtn') as HTMLElement;

    // 检索数据
    searchBtnEl.addEventListener('click', function (e: Event) {
        keyword = (document.querySelector('[name="keyword"]') as HTMLInputElement).value;

        if (!keyword) {
            renderTable(students);
            return;
        }

        searchStudents = students.filter(item => item.name.includes(keyword));
        console.log(searchStudents, 'searchStudents');
        renderTable(searchStudents);
    });

    let isEditing = false; // 验证是否是编辑状态 - 默认是添加

    // 验证手机号  return:boolean
    function checkIphone(iphone: string): boolean {
        const reg = /^(?:(?:\+|00)86)?1\d{10}$/;
        return reg.test(iphone);
    }

    // 验证邮箱  return:boolean
    function checkEmail(email: string): boolean {
        const reg = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return reg.test(email);
    }

    // 渲染学生数据到表格 tbody
    function renderTable(_students: Student[]) {
        const tbody = document.querySelector('.studentTable tbody') as HTMLTableSectionElement;
        tbody.innerHTML = '';

        _students.forEach(student => {
            const row = document.createElement('tr');
            row.innerHTML = `
                    <td><input type="checkbox" onclick="checkBoxSelectedHandler()" class="selectStudent" data-id="${student.id}"></td>
                    <td>${student.id}</td>
                    <td>${student.name}</td>
                    <td>${student.gender}</td>
                    <td>${student.hobbies}</td>
                    <td>${student.email || ''}</td>
                    <td>${student.iphone || ''}</td>
                    <td>${student.age}</td>
                    <td>${student.create_at || ''}</td>
                    <td>${student.update_at || ''}</td>
                    <td>
                        <button onclick="openEditModal(${student.id})">Edit</button>
                        <button onclick="deleteStudent(${student.id})">Delete</button>
                    </td>
                `;
            tbody.appendChild(row);
        });
    }

    // 实现全选
    document.querySelector('.selectAll')?.addEventListener('change', function (e: Event) {
        const stusAllEl = document.querySelectorAll('.selectStudent') as NodeListOf<HTMLInputElement>;
        const allChecked = (e.target as HTMLInputElement).checked;
        stusAllEl.forEach(checkbox => {
            checkbox.checked = allChecked;
        });
    });

    // 打开表单模态框，并标识为添加操作
    document.querySelector('.openModalBtn')?.addEventListener('click', function () {
        document.querySelector('.modalTitle')!.textContent = '添加学生';
        document.querySelector('.studentModal')!.setAttribute('style', 'display: block');
        isEditing = false;
    });

    // 打开编辑表单模态框
    function openEditModal(id: number) {
        const student = students.find(s => s.id === id);
        if (student) {
            document.querySelector('.modalTitle')!.textContent = '修改学生';
            (document.querySelector('.studentIdToEdit') as HTMLInputElement).value = student.id.toString();
            (document.querySelector('[name="name"]') as HTMLInputElement).value = student.name;
            (document.querySelector('[name="gender"]') as HTMLSelectElement).value = student.gender;
            (document.querySelector('[name="hobbies"]') as HTMLInputElement).value = student.hobbies;
            (document.querySelector('[name="email"]') as HTMLInputElement).value = student.email || '';
            (document.querySelector('[name="iphone"]') as HTMLInputElement).value = student.iphone || '';
            (document.querySelector('[name="age"]') as HTMLInputElement).value = student.age.toString();

            document.querySelector('.studentModal')!.setAttribute('style', 'display: block');
            isEditing = true;
        }
    }

    // 处理提交的表单数据
    document.querySelector('.studentForm')?.addEventListener('submit', function (this: HTMLFormElement, event: Event) {
        event.preventDefault();

        const formData = new FormData(this); // 现在 this 的类型为 HTMLFormElement
        const data = Object.fromEntries(formData.entries());


        if (!checkEmail(data.email as string)) {
            alert('邮箱格式错误~！');
            return;
        }

        if (!checkIphone(data.iphone as string)) {
            alert('手机格式错误~！');
            return;
        }

        const id = (document.querySelector('.studentIdToEdit') as HTMLInputElement).value;

        if (data.name && data.gender && data.hobbies && data.age) {
            if (isEditing) {
                const student = students.find(s => s.id === parseInt(id));
                if (student) {
                    student.name = data.name as string;
                    student.gender = data.gender as string;
                    student.hobbies = data.hobbies as string;
                    student.email = data.email as string;
                    student.iphone = data.iphone as string;
                    student.update_at = getFormattedCurrentDateTime();
                    student.age = parseInt(data.age as string);
                }
                isEditing = false;
            } else {
                students.push({
                    id: students.length ? students[students.length - 1].id + 1 : 1,
                    name: data.name as string,
                    gender: data.gender as string,
                    hobbies: data.hobbies as string,
                    email: data.email as string,
                    iphone: data.iphone as string,
                    create_at: getFormattedCurrentDateTime(),
                    update_at: getFormattedCurrentDateTime(),
                    age: parseInt(data.age as string)
                });
            }

            if (keyword) {
                renderTable(searchStudents);
            } else {
                renderTable(students);
            }

            setStudentsDataCache();
            document.querySelector('.studentModal')!.setAttribute('style', 'display: none');
            clearModal();
        } else {
            alert('请填充所有的字段');
        }
    });

    function clearModal() {
        (document.querySelector('.studentForm') as HTMLFormElement).reset();
        (document.querySelector('.studentIdToEdit') as HTMLInputElement).value = '';
    }

    function deleteStudent(id: number) {
        const index = students.findIndex(s => s.id === id);
        if (index !== -1) {
            students.splice(index, 1);
            if (keyword) {
                renderTable(searchStudents);
            } else {
                renderTable(students);
            }
            setStudentsDataCache();
        }
    }

    if (getStudentsDataCache()) {
        students = getStudentsDataCache()!;
    }

    renderTable(students);
    setStudentsDataCache();

    window.onclick = function (event: MouseEvent) {
        const modal = document.querySelector('.studentModal') as HTMLElement;
        if (event.target === modal) {
            modal.style.display = 'none';
            clearModal();
        }
    };

    function getFormattedCurrentDateTime(): string {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

    function setStudentsDataCache() {
        localStorage.setItem('student-data', JSON.stringify(students));
    }

    function getStudentsDataCache(): Student[] | null {
        const lstuData = localStorage.getItem('student-data');
        return lstuData ? JSON.parse(lstuData) : null;
    }

    // 示例用法
    // console.log(getFormattedCurrentDateTime()); // 输出: 2024-08-14 12:34:56

    // 0. 搞懂每一行代码 ，打上注释
    // 1. 修正模态框布局样式和整体bug样式，尽量让按钮 Input框美观些（1）提示：盒子模型计算
    // 2. 学生信息增加手机号和邮箱字段列 并在添加和修改的时候验证手机号和邮箱格式-正则
    // 3. 学生信息增加 创建时间和修改时间列 格式【YYYY-MM-DD HH:mm:ss】
    // 4. 列表的右上角增加 input框，搜索按钮，可以使用 name 检索数据，无检索关键词直接点击搜索按钮则默认检索所有数据
    // 5. 讲学生信息存入 localStorage ，使用JSON格式，关闭打开浏览器数据依然在
    // 6. 多选按钮样式和实际选择数据同步（可放最后）
}